package com.zygk.xmpp.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnInfoListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.mabeijianxi.smallvideorecord2.DeviceUtils;
import com.mabeijianxi.smallvideorecord2.FileUtils;
import com.mabeijianxi.smallvideorecord2.MediaRecorderActivity;
import com.mabeijianxi.smallvideorecord2.MediaRecorderBase;
import com.mabeijianxi.smallvideorecord2.StringUtils;
import com.mabeijianxi.smallvideorecord2.SurfaceVideoView;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.ToastUtil;
import com.zygk.xmpp.R;
import com.zygk.xmpp.R2;
import com.zygk.xmpp.constant.Urls;
import com.zygk.xmpp.dao.UploadLogic;
import com.zygk.xmpp.model.M_ChatItem;
import com.zygk.xmpp.model.apimodel.APIM_uploadFile;
import com.zygk.xmpp.util.HttpRequest;
import com.zygk.xmpp.xmpp.XMPP;

/**
 * 通用单独播放界面
 *
 * @author tangjun
 */
public class VideoPlayerActivity extends BaseActivity
    implements SurfaceVideoView.OnPlayStateListener, OnErrorListener, OnPreparedListener,
    OnCompletionListener, OnInfoListener {

  /**
   * 播放控件
   */
  @BindView(R2.id.videoview) SurfaceVideoView mVideoView;
  /**
   * 暂停按钮
   */
  @BindView(R2.id.play_status) ImageView mPlayerStatus;
  @BindView(R2.id.loading) ProgressBar mLoading;

  /**
   * 播放路径
   */
  private String mPath;
  /**
   * 是否需要回复播放
   */
  private boolean mNeedResume;

  private AlertDialog dialog;
  private int chatType = M_ChatItem.CHAT;

  @Override public void setContentView() {
    // 防止锁屏
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    mPath = getIntent().getStringExtra(MediaRecorderActivity.VIDEO_URI);
    if (StringUtils.isEmpty(mPath)) {
      finish();
      return;
    }

    setContentView(R.layout.xmpp_activity_video_player);
  }

  @Override public void init() {
    int screenWidth = getScreenWidth(this);
    int videoHight = (int) (screenWidth / (MediaRecorderBase.SMALL_VIDEO_HEIGHT
        / (MediaRecorderBase.SMALL_VIDEO_WIDTH * 1.0f)));
    mVideoView.getLayoutParams().height = videoHight;
    mVideoView.requestLayout();

    mVideoView.setOnPreparedListener(this);
    mVideoView.setOnPlayStateListener(this);
    mVideoView.setOnErrorListener(this);
    mVideoView.setOnInfoListener(this);
    mVideoView.setOnCompletionListener(this);

    mVideoView.setVideoPath(mPath);
  }

  public int getScreenWidth(Activity context) {
    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
    context.getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
    int W = mDisplayMetrics.widthPixels;
    return W;
  }

  @Override public void onResume() {
    super.onResume();
    if (mVideoView != null && mNeedResume) {
      mNeedResume = false;
      if (mVideoView.isRelease()) {
        mVideoView.reOpen();
      } else {
        mVideoView.start();
      }
    }
  }

  @Override public void onPause() {
    super.onPause();
    if (mVideoView != null) {
      if (mVideoView.isPlaying()) {
        mNeedResume = true;
        mVideoView.pause();
      }
    }
  }

  @Override protected void onDestroy() {
    if (mVideoView != null) {
      mVideoView.release();
      mVideoView = null;
    }
    super.onDestroy();
  }

  @Override public void onPrepared(MediaPlayer mp) {
    mVideoView.setVolume(SurfaceVideoView.getSystemVolumn(this));
    mVideoView.start();
    // new Handler().postDelayed(new Runnable() {
    //
    // @SuppressWarnings("deprecation")
    // @Override
    // public void run() {
    // if (DeviceUtils.hasJellyBean()) {
    // mVideoView.setBackground(null);
    // } else {
    // mVideoView.setBackgroundDrawable(null);
    // }
    // }
    // }, 300);
    mLoading.setVisibility(View.GONE);
  }

  @Override public boolean dispatchKeyEvent(KeyEvent event) {
    switch (event.getKeyCode()) {// 跟随系统音量走
      case KeyEvent.KEYCODE_VOLUME_DOWN:
      case KeyEvent.KEYCODE_VOLUME_UP:
        mVideoView.dispatchKeyEvent(this, event);
        break;
    }
    return super.dispatchKeyEvent(event);
  }

  @Override public void onStateChanged(boolean isPlaying) {
    mPlayerStatus.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
  }

  @Override public boolean onError(MediaPlayer mp, int what, int extra) {
    if (!isFinishing()) {
      // 播放失败
    }
    finish();
    return false;
  }

  @Override public void onBackPressed() {
    hesitate();
  }

  private void hesitate() {
    if (dialog == null) {
      dialog = new AlertDialog.Builder(this).setTitle(R.string.hint)
          .setMessage(R.string.record_camera_exit_dialog_message)
          .setNegativeButton(R.string.record_camera_cancel_dialog_yes,
              new DialogInterface.OnClickListener() {

                @Override public void onClick(DialogInterface dialog, int which) {
                  FileUtils.deleteDir(mPath);
                  finish();
                }
              })
          .setPositiveButton(R.string.record_camera_cancel_dialog_no, null)
          .setCancelable(false)
          .show();
    } else {
      dialog.show();
    }
  }

  @Override public void onCompletion(MediaPlayer mp) {
    if (!isFinishing()) mVideoView.reOpen();
  }

  @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override
  public boolean onInfo(MediaPlayer mp, int what, int extra) {
    switch (what) {
      case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
        // 音频和视频数据不正确
        break;
      case MediaPlayer.MEDIA_INFO_BUFFERING_START:
        if (!isFinishing()) mVideoView.pause();
        break;
      case MediaPlayer.MEDIA_INFO_BUFFERING_END:
        if (!isFinishing()) mVideoView.start();
        break;
      case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
        if (DeviceUtils.hasJellyBean()) {
          mVideoView.setBackground(null);
        } else {
          mVideoView.setBackgroundDrawable(null);
        }
        break;
    }
    return false;
  }

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // TODO: add setContentView(...) invocation
    ButterKnife.bind(this);
  }

  @OnClick({ R2.id.txt_right, R2.id.play_status, R2.id.root, R2.id.videoview })
  public void onViewClicked(View v) {
    if (v.getId() == R.id.videoview) {
      if (mVideoView.isPlaying()) {
        mVideoView.pause();
      } else {
        mVideoView.start();
      }
    } else if (v.getId() == R.id.play_status) {
      mVideoView.start();
    } else if (v.getId() == R.id.txt_right) {
      UploadLogic.upload(mContext, mPath, Urls.UPLOAD_VIDEO, new HttpRequest.HttpCallback() {
        @Override public void onStart() {
          showPd();
        }

        @Override public void onSucceed(Object obj) {
          APIM_uploadFile result = (APIM_uploadFile) obj;
          XMPP.sendVideoMsg(result.getResults(), chatType);
          finish();
        }

        @Override public void onFailed() {
          ToastUtil.showNetErrorMessage(mContext);
        }

        @Override public void onFinish() {
          dismissPd();
        }
      });
    } else if (v.getId() == R.id.root) {
      hesitate();
    }
  }
}
